
//
//  UILabel+DFExtension.m
//  Pods
//
//  Created by rujia chen on 17/4/9.
//
//

#import "UILabel+DFExtension.h"
#import <objc/runtime.h>
#import "NSObject+DFSwizzle.h"

static char *kPropertyTextBoundsBlock = "kPropertyTextBoundsBlock";
static char *kPropertyDrawTextInRectWithBlock = "kPropertyDrawTextInRectWithBlock";
static char *kPropertyPaddingInsets = "kPropertyPaddingInsets";
@implementation UILabel (DFExtension)

+ (void)load {
    [self df_swizzleMethod:@selector(textRectForBounds:limitedToNumberOfLines:) withMethod:@selector(df_textRectForBounds:limitedToNumberOfLines:) error:nil];
    [self df_swizzleMethod:@selector(drawTextInRect:) withMethod:@selector(df_drawTextInRect:) error:nil];
}

- (void)df_setPaddingInset:(UIEdgeInsets)paddingInset {
    objc_setAssociatedObject(self, kPropertyPaddingInsets, [NSValue valueWithUIEdgeInsets:paddingInset], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self df_setTextRectForBoundsWithBlock:^CGRect(CGRect rect, NSInteger numberOfLines) {
        rect.size.width -= (paddingInset.left + paddingInset.right);
        CGRect result = [self df_textRectForBounds:rect limitedToNumberOfLines:numberOfLines];
        result.size.width += (paddingInset.left + paddingInset.right);
        result.size.height += (paddingInset.top + paddingInset.bottom) ;
        return result;
    }];
    [self df_setDrawTextInRectWithBlock:^(CGRect rect) {
        [self df_drawTextInRect:UIEdgeInsetsInsetRect(rect, paddingInset)];
    }];
    
}

- (UIEdgeInsets)df_paddingInset {
    return [objc_getAssociatedObject(self, kPropertyPaddingInsets) UIEdgeInsetsValue];
}

#pragma mark - setter

- (void)df_setTextRectForBoundsWithBlock:(TextBoundsBlock)block {
    objc_setAssociatedObject(self, kPropertyTextBoundsBlock, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)df_setDrawTextInRectWithBlock:(DrawTextInRectBlock)block {
    objc_setAssociatedObject(self, kPropertyDrawTextInRectWithBlock, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

#pragma mark - swizzle impl

- (void)df_drawTextInRect:(CGRect)rect {
    DrawTextInRectBlock block = objc_getAssociatedObject(self, kPropertyDrawTextInRectWithBlock);
    if (!block) {
        [self df_drawTextInRect:rect];
    }else {
        block(rect);
    }
}

- (CGRect)df_textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines{
    TextBoundsBlock block = objc_getAssociatedObject(self, kPropertyTextBoundsBlock);
    if (!block) {
        return [self df_textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    }else {
        return block(bounds, numberOfLines);
    }
}

@end
